﻿using UnityEngine;
using System.Collections;
using Game.Scripts.Managers;
using FrenzyIsland.UI;
using Assets.components;

public class BuildingPreviewController : MonoBehaviour {
    
    public UIButton buttonConfirm;
    public UIButton buttonCancel;

    private GameObject buildingPreview;                 //mantiene il riferimento per distruggerlo
    private DragBuildingController dragController;      //chiede se può essere costruito

    /// <summary>
    /// Aggiunge un controller sull'edificio che si vuole costruire
    /// </summary>
    /// <param name="buildingPreview"> 
    ///     Edificio prototipo che si vuole costruire 
    /// </param>
    /// <returns></returns>
    public static BuildingPreviewController SetComponent(GameObject buildingPreview)
    {
        //chiedo il prefab da aggiungere sul gameobject
        CameraRigAction cameraRigAction = Camera.main.GetComponent<CameraRigAction>();
        GuiManager guiManager = UIRoot.list[0].GetComponent<GuiManager>();
        GameObject prefab = BuildingManager.instance.UIBuildingPreviewWidget;
        GuiManager.TypePlaceHolders type = GuiManager.TypePlaceHolders.Building;

        //aggiungo il follow target sopra l'oggetto creato e imposto i riferimenti al controller
        GameObject widget = guiManager.AddFollowTarget(type, prefab, buildingPreview);
        BuildingPreviewController bpc = widget.GetComponent<BuildingPreviewController>();
        bpc.buildingPreview = buildingPreview;

        //aggiungo al building il controller per ii drag
        bpc.dragController = DragBuildingController.CreateComponent(buildingPreview);

        //mi faccio guardare
        cameraRigAction.focusOnObject(buildingPreview);

        return bpc;
    }

    public void Close_Click()
    {
        Destroy(buildingPreview);
    }

    public void Confirm_Click()
    {
        Destroy(buildingPreview);

        //istanzia l'oggetto
        Building building = buildingPreview.GetComponent<Building>();
        Vector3 p = buildingPreview.transform.position + Vector3.down * 0.5f + Vector3.right * 0.5f;
        building.prototype.instantiateBuildingAt(p.x,p.y,p.z);

    }

    public UIButtonColor.State buttonState {
        get
        {
            if (dragController.IsBuildingAllowed)
                return UIButtonColor.State.Normal;
            else
                return UIButtonColor.State.Disabled;
        }
    }

    public bool IsBuildingAllowed {
        get { return dragController.IsBuildingAllowed; }
    }

    public Color ColorState
    {
        get
        {
            if (dragController.IsBuildingAllowed)
                return new Color(1f, 1f, 1f);
            else
                return new Color(0.5f, 0.5f, 0.5f);
        }
    }

}
